package com.shigu.wx.web.services;

import com.alibaba.fastjson.JSON;
import com.opentae.data.mall.beans.MoOverallSituation;
import com.opentae.data.mall.interfaces.MoOverallSituationMapper;
import com.shigu.wx.web.WxTempleateBaseData;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.sword.wechat4j.api.WechatClient;
import org.sword.wechat4j.api.request.Cgi_binTokenGet;
import org.sword.wechat4j.api.request.message.Cgi_binMessageTemplateSendPost;
import org.sword.wechat4j.api.response.Token;

import java.io.IOException;
import java.util.Map;

@Service
public class WxTokenService {
    private static final Logger logger = LoggerFactory.getLogger(WxTokenService.class);

    @Value("${wechat.appid}")
    private String APP_ID;

    @Value("${wechat.appsecret}")
    private String APP_SECRET;

    @Autowired
    private MoOverallSituationMapper moOverallSituationMapper;

    @Cacheable(value = "wx_token_cach")
    public Token getSystemToken() throws IOException {
        WechatClient client = new WechatClient();
        Cgi_binTokenGet cgi_binTokenGet=new Cgi_binTokenGet();
        cgi_binTokenGet.setAppid(APP_ID);
        cgi_binTokenGet.setSecret(APP_SECRET);
        MoOverallSituation situation=new MoOverallSituation();
        situation.setSituationId(1L);
        Token token=client.execute(cgi_binTokenGet);
        situation.setAccessToken(token.getAccess_token());
        moOverallSituationMapper.updateByPrimaryKeySelective(situation);
        return token;
    }

    /**
     * 发送模板消息
     * @param templateId
     * @param openid
     * @param wxTempleateDataMap
     * @param url
     * @param accessToken
     */
    public void sendTemplateMsg(String templateId,String openid,
                                Map<String,WxTempleateBaseData> wxTempleateDataMap,String url,String accessToken){
        Cgi_binMessageTemplateSendPost send=new Cgi_binMessageTemplateSendPost();
        send.setTemplate_id(templateId);
        send.setTouser(openid);//openid
        send.setData(JSON.toJSONString(wxTempleateDataMap));
        send.setUrl(url);
        WechatClient client=new WechatClient();
        try {
            client.execute(send,accessToken);
        } catch (IOException e) {
            logger.error("模板消息发送失败"+JSON.toJSONString(wxTempleateDataMap),e);
        }
    }
}
